<template>
  <div class="container" style="height: 100vh;width: 300px;padding: 20px;box-sizing: border-box;width: 100%;">
    <header>
      <MBreadcrumb :item="breadcrumbItem" />
    </header>
    <main>
      <MTitle class="title">
        <template #left>
          生产计划
        </template>
      </MTitle>
      <form>
        <table id="attributeTable" class="mtable">
          <tr v-for="(obj, index) in MListItem" :key="index" class="mtr">
            <td class="field">{{ obj.field }}</td>
            <td class="value">
              <MInput v-model="ProductInfo[index]" style="font-size: 12px;width: 100%" disabled>
              </MInput>
            </td>
          </tr>
        </table>
      </form>
      <MTitle class="title">
        <template #left>
          所需物料
        </template>
      </MTitle>
      <MTable :headers="tableHeaders" :rows="tableRows" style="margin-top: 20px;" />
    </main>
    <footer>
      <div style=" text-align: center;margin-top: 20px;" v-if="!isDisable">
        <MButton @click="makePlan" v-if="!isMake && !isTransfer">生成需求计划</MButton>
        <div v-if="isMake">
          <MButton @click="printPlan" v-if="!isPrint">打印物料计划</MButton>

        </div>
        <MButton @click="transferPurchase" v-if="isTransfer">转交采购员</MButton>
      </div>
    </footer>
    <MMessage v-if="toastVisible" :message="toastMessage" :state="toastState" />

  </div>
</template>

<script>
import { ref, onMounted } from 'vue';
import MBreadcrumb from "../../components/MBreadcrumb.vue"
import MTitle from "../../components/MTitle.vue"
//import MList from "../../components/MList.vue"
import MButton from "../../components/MButton.vue"
import MInput from "../../components/MInput.vue"
import MMessage from '../../components/MMessage.vue';
import MTable from '../../components/MTable.vue';
//import MDateTime from '../../components/MDateTime.vue';
//import MTag from "../../components/MTag.vue"
import axios from "../../axios/axios"
export default {
  name: "ProduceInfo",
  components: {
    MBreadcrumb,
    MTitle,
    MTable,
    MButton,
    MInput,
    MMessage,
    //MTag
    //MIcon
  },
  setup() {
    const toastVisible = ref(false)
    const toastMessage = ref("")
    const toastState = ref("success")
    const breadcrumbItem = {
      key: "0",
      title: '赋码管理',
      children: {
        key: "0-0",
        title: '生产计划',
      }
    }
    const MListItem =
      [
        { "field": "计划编号", "isDisabled": true },
        { "field": "订单编号", "isDisabled": true },
        { "field": "接单日期", "isDisabled": true },
        { "field": "产品型号", "isDisabled": true },
        { "field": "订单数量", "isDisabled": true },
        { "field": "客户名称", "isDisabled": true },
        { "field": "排产日期", "isDisabled": true },
        { "field": "加工车间", "isDisabled": true },
      ]
    const tableHeaders = [
      { id: 1, text: '物料名称', width: "28%" },
      { id: 2, text: '规格', width: "36%" },
      { id: 3, text: '数量', width: "18%" },
      { id: 4, text: '库存', width: "18%" }
    ]
    const tableRows = ref([
      ['液晶面板', '75英寸，4K Ultra HD分辨率', '1', "1"],
      ['背光模组', 'LED背光，包含灯条、反射片等', '1', "1"],
      ['驱动电路板', '主控板、电源板等', '0', '0'],
      ['音频电路板', '负责音频处理和输出', '1', '1'],
      ['外壳', '包括前壳、后壳、底座等', '1', '1'],
      ['喇叭', '负责音频播放', '2', '2'],
      ['遥控器', '红外线遥控器', '1', '1'],
      ['电源线', '连接电视和电源插座', '1', '1'],
      ['AV线', '连接电视和音频/视频设备', '1', '1'],
      ['HDMI线', '高清多媒体接口线', '1', '1'],
      ['螺丝及紧固件', '用于固定电视内部和外部组件', '0', '0'],
      ['缓冲材料', '用于保护电视在运输过程中的安全', '0', '0'],
      ['包装材料', '包括纸箱、泡沫、防尘袋等', '1', '1'],
      ['用户手册', '包含使用说明和保修信息', '1', '1'],
      ['其他辅料', '如胶带、标签等', '0', '0']
    ])
    const ProductInfo = ref(["", "", "", "", "", "", ""])
    const tagItems = ref([])
    const params = ref([])
    const userId = ref("")
    const orderInfo = ref({})
    const isMake = ref(false)
    const isPrint = ref(false)
    const isDisable = ref(false)
    const isTransfer = ref(false)

    const printPlan = () => {
      axios.get("/step/sendstep?type=printOrder&userId=" + params.value.get('userId') + "&trainingId=" + params.value.get('trainingId')).then(res => {
        if (res.data.Code === "200") {
          messageShow("已打印", "success")
          isPrint.value = true
        }
      })
    }
    const transferPurchase = () => {
      axios.get("/step/sendstep?type=transferPurchase&userId=" + params.value.get('userId') + "&trainingId=" + params.value.get('trainingId')).then(res => {
        if (res.data.Code === "200") {
          messageShow("已转交采购", "success")
        }
      })
    }
    const makePlan = () => {
      var info = []
      tableRows.value.map(e => {
        info.push({
          name: e[0],
          value: e[1],
          number: e[2]
        })
      })
      axios.post('/material/save', {
        plannumber: ProductInfo.value[0],
        materialinfo: JSON.stringify(info)
      })
        .then(response => {
          if (response.data.Code == "200") {
            messageShow("已生成物料需求计划", "success")
            isMake.value = true
          } else {
            messageShow(response.data.Msg, "warning")
          }
        })
    }

    const messageShow = (msg, state) => {
      toastMessage.value = msg;
      toastVisible.value = true;
      toastState.value = state
      // 使用 setTimeout 模拟 Toast 组件内部的定时器功能（仅用于演示）
      // 在实际使用中，你应该依赖 Toast 组件内部的定时器
      setTimeout(() => {
        toastVisible.value = false;
      }, 3000); // 与 Toast 组件中的 duration 属性保持一致
    }
    onMounted(() => {
      // 获取 URL 参数
      const param = new URLSearchParams(window.location.search);
      params.value = param
      if (param.has('userId')) {
        userId.value = param.get('userId');
      }
      if (param.has('isDisable')) {
        isDisable.value = param.get('isDisable') === "true"
      }
      if (param.get('targetPageId') === "transferPurchase") {
        isTransfer.value = true
      }
      axios.get('/order/select?userId=' + param.get('userId') + "&trainingId=" + param.get('trainingId') + "&isPart=0")
        .then(response => {
          var info = response.data.Data
          axios.get('/produce/selectbyinfo?userId=' + param.get('userId') + "&trainingId=" + param.get('trainingId'))
            .then(response => {
              var data = response.data.Data
              orderInfo.value = data
              ProductInfo.value = [data.plannumber, data.ordernumber, data.plantime, info.productmodel, info.goodsnumber, info.companyname, data.producetime, data.produceworkshop]
              var tableInfo = [...tableRows.value]
              for (var i = 0; i < tableInfo.length; i++) {
                if (i === 0) {
                  tableInfo[i][2] = String(Number(tableInfo[i][2]) * info.goodsnumber)
                  tableInfo[i][3] = "0"
                  continue
                }
                if (tableInfo[i][2] !== "0") {
                  tableInfo[i][2] = String(Number(tableInfo[i][2]) * info.goodsnumber)
                  tableInfo[i][3] = String(Number(tableInfo[i][3]) * info.goodsnumber + 100)
                } else {
                  tableInfo[i][2] = "若干"
                  tableInfo[i][3] = "若干"
                }
              }
              tableRows.value = tableInfo
            })
        })

    });
    return {
      toastVisible,
      toastMessage,
      toastState,
      breadcrumbItem,
      MListItem,
      tagItems,
      ProductInfo,
      tableHeaders,
      tableRows,
      isMake,
      isPrint,
      isDisable,
      isTransfer,
      makePlan,
      transferPurchase,
      printPlan
    };
  },
};
</script>

<style scoped>
.title {
  margin-top: 30px;
}

.title1 {
  margin-top: 20px;
}

.mtr {
  display: flex;
  flex-wrap: wrap;
  /* 允许子元素换行 */
  align-items: flex-start;
}

.container {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
}

footer {
  text-align: center;
  height: 10%;
}

main {
  flex: 1;
}

.mtable {
  width: 100%;
  font-size: 13px;

}

.field {
  text-align: left;
  padding: 4px 0;
  flex: 1 1 60px;
  word-break: break-word;
  /* 允许长单词换行 */
  overflow-wrap: break-word;
  min-width: 0;
  /* 确保内容可以缩小 */
  height: 26px;
  line-height: 26px;
}

.value {
  text-align: right;
  padding: 4px 0;
  flex: 1 1 190px;
  word-break: break-word;
  /* 允许长单词换行 */
  overflow-wrap: break-word;
  min-width: 0;
  height: 26px;
  line-height: 26px;
  /* 确保内容可以缩小 */
}
</style>